import {BrowseVueLoader} from "./BrowseVueLoader";
import {loaderCallBack} from "./CommonUtils";

export type HttpUtilsCoreType = (url: string) => Promise<string>

/**
 * 重写httpUtils请求的内核
 * @param call
 */
export function rewriteHttpUtilsCore(call: HttpUtilsCoreType) {
  httpUtilsCore = call
}

let httpUtilsCore: HttpUtilsCoreType = (url: string) => {
  return new Promise<string>((resolve, reject) => {
    if (BrowseVueLoader.version) {
      url += `?_v=${BrowseVueLoader.version}`
    }
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url); // 发送异步请求
    // 设置输出位utf-8
    xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    xhr.responseType = 'text'; // 这个异步请求才可以用
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
          resolve(xhr.responseText);
        } else {
          reject(xhr.status);
        }
      }
    };
    xhr.send(null);
  })
}

export function httpUtils(url: string): Promise<string> {
  loaderCallBack(false, url)
  return new Promise<string>((resolve, reject) => {
    httpUtilsCore(url)
      .then(res => {
        resolve(res)
      }).catch(reject)
      .finally(() => {
        loaderCallBack(true, url)
      })
  })
}
